package
{
	public class InstanceLearner
	{
		public function InstanceLearner();
		private var mInstances:Vector.<Instance> = new Vector.<Instance>();
		
		/**
		 * Add an instance to the learner
		 * 
		 * @param instance
		 */
		public function addInstance(instance:Instance):void {
			mInstances.push(instance);
		}
		
		/**
		 * Retrieve all the instances
		 * 
		 * @return instances
		 */
		public function getInstances():Vector.<Instance> {
			return mInstances;
		}
		
		/**
		 * Remove an instance based on its label
		 * 
		 * @param label
		 */
		public function removeInstance(label:String):void {
			var instances:Vector.<Instance> = mInstances;
			var count:int = instances.length;
			for (var i:int = 0; i < count; i++) {
				var instance:Instance = instances[i];
				if (label == instance.label) {
					instances.splice(i,1);
					return;
				}
			}
		}
		
		public function clearInstance():void{
			mInstances = new Vector.<Instance>();
		}
		
		
		
		public function classify(vector:Vector.<Number>):Instance{
			var instances:Vector.<Instance> = getInstances();
			var predictions:Vector.<Instance> = new Vector.<Instance>();
			var count:int = instances.length;
			if(count==0){
				throw "没有模版库，不能比较";
			}
			for (var i:int = 0; i < count; i++) {
				var sample:Instance = instances[i];
				if (sample.vector.length != vector.length) {
					continue;
				}
				var distance:Number;
//					distance = GestureUtils.minimumCosineDistance(sample.vector, vector);
					distance = GestureUtils.squaredEuclideanDistance(sample.vector, vector);
				var weight:Number;
				if (distance == 0) {
					weight = Number.MAX_VALUE;
				} else {
					weight = 1 / distance;
				}
				sample.score = weight;
				predictions.push(sample);
			}
			
			if(predictions.length>0){
				predictions.sort(compare);
				trace(predictions.length);
				return predictions[0];
			}else{
				return null;
			}
		}
		
		private function compare(object1:Instance, object2:Instance):int {
			var score1:Number = object1.score;
			var score2:Number = object2.score;
			if (score1 > score2) {
				return -1;
			} else if (score1 < score2) {
				return 1;
			} else {
				return 0;
			}
		}

	}
}